package com.squirrel.serialportcore.machine.consumer;


import com.squirrel.serialportcore.common.CommonBase;
import com.squirrel.serialportcore.common.ContentBase;
import com.squirrel.serialportcore.entity.mapper.PortQueueMapper;
import com.squirrel.serialportcore.exception.CoreException;
import com.squirrel.serialportcore.utils.StreamUtils;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

/**
 * 串口监听 继承线程类 实现监听接口
 * 因为该实现对象会导致新线程 所以需要包含初始化数据在该对象内部
 *
 * @author Squbi
 * @date 2021/2/25 9:40
 */
public class SerialPortListener implements SerialPortEventListener {
    private static Logger logger = LoggerFactory.getLogger(SerialPortListener.class);

    private String portName;
    private SerialPort serialPort;
    private RabbitTemplate rabbitTemplate;

    public SerialPortListener(String portName, RabbitTemplate rabbitTemplate) {
        this.portName = portName;
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 该方法是该 {@link SerialPortEventListener} 接口的实现方法
     * 以创建一个监听器 对串口的返回信息进行处理
     *
     * @param serialPortEvent 接口传入 串口事件
     * @author Squbi
     * @date 2021/2/25 9:42
     */
    @Override
    public void serialEvent(SerialPortEvent serialPortEvent) {
        if (!CommonBase.isTotalInit()) {
            return;
        }
        if (serialPort == null && ContentBase.getSerialPortMap().containsKey(portName)) {
            this.serialPort = ContentBase.getSerialPortMap().get(portName);
        }
        long threadId = Thread.currentThread().getId();
        //获取事件类型
        int eventType = serialPortEvent.getEventType();
        logger.debug(" -debug- 线程 {} 串口名 {} 串口 {} 触发了监听器 事件 {}", threadId, portName, serialPort, eventType);
        switch (eventType) {
            case SerialPortEvent.BI:
            case SerialPortEvent.OE:
            case SerialPortEvent.FE:
            case SerialPortEvent.PE:
            case SerialPortEvent.CD:
            case SerialPortEvent.CTS:
            case SerialPortEvent.DSR:
            case SerialPortEvent.RI:
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                throw new CoreException(logger, " 线程 {} 串口 {} 获取到无法处理事件 {} ", threadId, portName, eventType);
            case SerialPortEvent.DATA_AVAILABLE:
                // 当传递事件表示有可用数据时读取数据
                byte[] readBuffer = new byte[0];
                InputStream inputStream = null;
                try {
                    assert serialPort != null;
                    inputStream = serialPort.getInputStream();
                    int available = inputStream.available();
                    while (available > 0) {
                        readBuffer = StreamUtils.readFromPort(serialPort);
                        available = inputStream.available();
                    }
                    String readStr = Arrays.toString(readBuffer);
                    logger.info(" <-| 线程 {} 串口 {} 监听器收到的数据为 {}", threadId, portName, readStr);
                    PortQueueMapper portQueueMapper = CommonBase.getPortQueueName().get(portName);
                    String outR = portQueueMapper.getOutR();
                    rabbitTemplate.setExchange(portQueueMapper.getOutE());
                    rabbitTemplate.convertAndSend(outR, readBuffer);
                    logger.info(" <--| 线程 {} 串口 {} 已发送消息 {} 至ROUTER {}", threadId, portName, readStr, outR);
                } catch (Exception e) {
                    throw new CoreException(logger, " 线程 {} 串口 {} 监听到事件 {} 解析事件异常 {}", threadId, portName, eventType, e);
                } finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;
            default:
                break;
        }
    }
}
